import { useEffect, useState } from 'react';
import {
  Table,
  Button,
  Space,
  Input,
  Tag,
  Modal,
  message,
  Badge,
} from 'antd';
import {
  EyeOutlined,
  DeleteOutlined,
  ExperimentOutlined,
  FileTextOutlined,
  MedicineBoxOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import {
  getRecordsList,
  deleteRecord,
  evaluateRecord,
  type RecordListItem,
  type RecordQueryParams,
  EvaluationMode,
} from '@/api';

const { Search } = Input;

const RecordList = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [records, setRecords] = useState<RecordListItem[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchParams, setSearchParams] = useState<RecordQueryParams>({});
  const [evaluating, setEvaluating] = useState<string | null>(null);
  const [pollingInterval, setPollingInterval] = useState<number | null>(null);

  useEffect(() => {
    loadRecords();
  }, [currentPage, pageSize, searchParams]);

  // 评估进行中时，定时轮询刷新列表
  useEffect(() => {
    if (evaluating) {
      // 每3秒刷新一次列表
      const interval = setInterval(() => {
        loadRecords();
      }, 3000);
      setPollingInterval(interval);
      
      return () => {
        if (interval) clearInterval(interval);
      };
    } else {
      if (pollingInterval) {
        clearInterval(pollingInterval);
        setPollingInterval(null);
      }
    }
  }, [evaluating]);

  const loadRecords = async () => {
    try {
      setLoading(true);
      const response = await getRecordsList({
        ...searchParams,
        page: currentPage,
        page_size: pageSize,
      });
      const data = response.data.data;
      setRecords(data.items);
      setTotal(data.total);
    } catch (error) {
      console.error('加载病历列表失败:', error);
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value: string) => {
    setSearchParams({ ...searchParams, patient_name: value || undefined });
    setCurrentPage(1);
  };

  const handleEvaluate = async (record: RecordListItem) => {
    Modal.confirm({
      title: '选择评估模式',
      content: (
        <div>
          <p><strong>推荐：混合评估</strong>（速度快，准确度高）</p>
          <p>• 规则评估：瞬间完成，基础检查</p>
          <p>• AI评估：约30-120秒，深度分析</p>
          <p>• 混合评估：约10-60秒，综合优势</p>
        </div>
      ),
      okText: '使用混合评估（推荐）',
      cancelText: '使用AI评估',
      width: 500,
      onOk: () => startEvaluation(record, EvaluationMode.HYBRID),
      onCancel: () => startEvaluation(record, EvaluationMode.AI_BASED),
    });
  };

  const startEvaluation = async (record: RecordListItem, mode: EvaluationMode) => {
    try {
      setEvaluating(record.id);
      const modeText = mode === EvaluationMode.HYBRID ? '混合评估' : 'AI评估';
      message.loading({
        content: `正在进行${modeText}，请稍候...（可以切换页面，评估在后台进行）`,
        key: 'evaluating',
        duration: 0,
      });
      
      const response = await evaluateRecord({
        record_id: record.id,
        evaluation_mode: mode,
      });
      
      message.success({
        content: '评估完成！',
        key: 'evaluating',
      });
      
      // 刷新列表
      await loadRecords();
      
      // 跳转到评估详情
      setTimeout(() => {
        navigate(`/assessment/${response.data.data.id}`);
      }, 500);
    } catch (error) {
      console.error('评估失败:', error);
      message.error({
        content: '评估失败，请重试',
        key: 'evaluating',
      });
    } finally {
      setEvaluating(null);
    }
  };

  const handleDelete = (record: RecordListItem) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除患者 "${record.patient_name}" 的病历吗？`,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteRecord(record.id);
          message.success('删除成功');
          loadRecords();
        } catch (error) {
          console.error('删除失败:', error);
          message.error('删除失败');
        }
      },
    });
  };

  const handleViewDetail = async (record: RecordListItem) => {
    // 如果有评估记录，跳转到报告页，否则跳转到病历详情
    if (record.has_assessment) {
      navigate(`/report/${record.id}`);
    } else {
      message.info('该病历尚未评估，请先进行评估');
    }
  };

  const columns: ColumnsType<RecordListItem> = [
    {
      title: '患者姓名',
      dataIndex: 'patient_name',
      key: 'patient_name',
      width: 120,
      render: (text) => (
        <span style={{ 
          display: 'flex', 
          alignItems: 'center', 
          gap: '6px',
          color: '#389e0d',
          fontWeight: 600,
        }}>
          <UserOutlined style={{ color: '#52c41a' }} />
          {text}
        </span>
      ),
    },
    {
      title: '性别',
      dataIndex: 'patient_gender',
      key: 'patient_gender',
      width: 80,
    },
    {
      title: '年龄',
      dataIndex: 'patient_age',
      key: 'patient_age',
      width: 80,
      render: (age) => (age !== null ? `${age}岁` : '-'),
    },
    {
      title: '科室',
      dataIndex: 'department',
      key: 'department',
      width: 150,
      ellipsis: true,
    },
    {
      title: '就诊日期',
      dataIndex: 'visit_date',
      key: 'visit_date',
      width: 180,
      render: (date) => (date ? new Date(date).toLocaleString('zh-CN') : '-'),
    },
    {
      title: '诊断',
      dataIndex: 'diagnosis',
      key: 'diagnosis',
      ellipsis: true,
      render: (diagnosis: string[]) => {
        if (!diagnosis || diagnosis.length === 0) return '-';
        return diagnosis.join('; ');
      },
    },
    {
      title: '评估状态',
      dataIndex: 'has_assessment',
      key: 'has_assessment',
      width: 100,
      render: (has_assessment: boolean) =>
        has_assessment ? (
          <Tag 
            color="success" 
            style={{ 
              background: '#f6ffed',
              borderColor: '#52c41a',
              color: '#389e0d',
              fontWeight: 500,
              padding: '2px 12px',
            }}
          >
            ✓ 已评估
          </Tag>
        ) : (
          <Tag 
            color="warning"
            style={{ 
              fontWeight: 500,
              padding: '2px 12px',
            }}
          >
            ⏱ 待评估
          </Tag>
        ),
    },
    {
      title: '操作',
      key: 'action',
      width: 240,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          {record.has_assessment ? (
            <Button
              type="link"
              icon={<FileTextOutlined />}
              onClick={() => navigate(`/report/${record.id}`)}
              style={{ color: '#52c41a' }}
            >
              查看报告
            </Button>
          ) : (
            <Button
              type="primary"
              size="small"
              icon={<ExperimentOutlined />}
              loading={evaluating === record.id}
              onClick={() => handleEvaluate(record)}
              style={{
                background: '#52c41a',
                borderColor: '#52c41a',
              }}
            >
              开始评估
            </Button>
          )}
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
            style={{ color: '#52c41a' }}
          >
            详情
          </Button>
          <Button
            type="link"
            danger
            size="small"
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ animation: 'fadeIn 0.6s ease-out' }}>
      <div style={{ marginBottom: 48, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <h1 className="page-title">病历管理</h1>
          <p className="page-subtitle">MEDICAL RECORDS</p>
        </div>
        <Badge 
          count={total} 
          showZero 
          style={{ 
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            boxShadow: '0 4px 12px rgba(102, 126, 234, 0.3)',
          }} 
        />
      </div>

      <div className="medical-card" style={{ padding: 32 }}>
        <div style={{ marginBottom: 32, display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'center' }}>
          <Search
            placeholder="搜索患者姓名..."
            allowClear
            enterButton="搜索"
            style={{ width: 320 }}
            onSearch={handleSearch}
            size="large"
          />
          <Button
            onClick={() => {
              setSearchParams({});
              setCurrentPage(1);
            }}
            size="large"
          >
            重置
          </Button>
          <div style={{ 
            marginLeft: 'auto', 
            display: 'flex', 
            gap: 24,
            alignItems: 'center',
          }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 24, fontWeight: 300, color: '#667eea' }}>
                {records.filter(r => r.has_assessment).length}
              </div>
              <div style={{ fontSize: 12, color: '#8F9BB3' }}>已评估</div>
            </div>
            <div style={{ width: 1, height: 30, background: '#E4E9F2' }}></div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 24, fontWeight: 300, color: '#FFAA00' }}>
                {records.filter(r => !r.has_assessment).length}
              </div>
              <div style={{ fontSize: 12, color: '#8F9BB3' }}>待评估</div>
            </div>
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={records}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          style={{
            background: '#ffffff',
          }}
          rowClassName={() => 'medical-card'}
          pagination={{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => (
              <span style={{ color: '#52c41a', fontWeight: 500 }}>
                <MedicineBoxOutlined style={{ marginRight: '6px' }} />
                共 {total} 条病历记录
              </span>
            ),
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size);
            },
          }}
        />
      </div>
    </div>
  );
};

export default RecordList;
